package cn.chinamobile.remote.assistance.mobile.communication;

import cn.chinamobile.remote.assistance.mobile.codec.Message;
import cn.chinamobile.remote.assistance.mobile.codec.RequestMessage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;

public final class CommunicationFilter extends BaseFilter {

    private Set<Connection> set = new HashSet<>();

    public CommunicationFilter() {
        ScheduledExecutorService downloadSchedule = Executors.newSingleThreadScheduledExecutor();
        downloadSchedule.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                for (final Connection c : set) {
                    c.write(new RequestMessage(15, "echo"));
                }
            }
        }, 1L, 5L, TimeUnit.SECONDS);
    }

    @Override
    public NextAction handleRead(FilterChainContext ctx) throws IOException {
        final Message message = ctx.getMessage();
        System.out.println(message.getClass().getName());
        System.out.println(Thread.currentThread().getName());
        set.add(ctx.getConnection());
        ctx.resumeNext();
        return ctx.getSuspendAction();
    }
}
